package main

import (
	"BlazeRider-backend/app"
	"BlazeRider-backend/app/controller"
	"BlazeRider-backend/app/db"
	"BlazeRider-backend/app/manager"
	"BlazeRider-backend/app/middleware"
	"BlazeRider-backend/config"
	"BlazeRider-backend/routes"
	"flag"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"strconv"
	"strings"
)

func main() {
	// 1. 定义并解析命令行参数
	var env string
	flag.StringVar(&env, "env", "dev", "运行环境（dev/prod）")
	flag.Parse()
	env = strings.ToLower(env) // 统一转为小写

	r := gin.Default()
	r.Use(middleware.RecoveryMiddleware())

	// 配置CORS中间件
	r.Use(CORSMiddleware())

	// 初始化配置（自动检测环境）
	if err := config.Init(env); err != nil {
		log.Fatalf("Failed to init config: %v", err)
	}

	// 获取配置
	cfg := config.Get()
	log.Printf("Running in %s mode on port %d", cfg.App.Env, cfg.App.Port)

	if cfg.App.Env == "prod" {
		gin.SetMode(gin.ReleaseMode) // 设置为 rease 模式
	}

	// 初始化所有Manager

	if cfg.Database.Enabled {
		err := db.Init()
		if err != nil {
			log.Fatalf("Failed to init database: %v", err)
		}
		defer db.GetDB().Close() // 确保关闭连接
	}

	manager.Init()

	r.Use(func(c *gin.Context) {
		fmt.Printf("[ROUTE] %s %s\n", c.Request.Method, c.Request.URL.Path)
		c.Next()
	})

	// 添加路由列表输出
	r.GET("/routes", func(c *gin.Context) {
		routes := r.Routes()
		c.JSON(200, routes)
	})

	controllers := []routes.Registrar{
		//controller.NewIndexController(managers),
		controller.NewIndexController(),
		controller.NewHttpController(),
		controller.NewdyPushController(),
	}

	app.RegistRoute(r, controllers)

	// 启动定时任务需要类型断言
	if ic, ok := controllers[0].(*controller.IndexController); ok {
		ic.StartTicker()
	}

	//if ic, ok := controllers[1].(*controller.HttpController); ok {
	//	ic.StartTicker()
	//}

	//app.RegistRoute(r, controllers)
	r.StaticFS("/static", http.Dir("./public"))
	r.Run(":" + strconv.Itoa(cfg.App.Port))
}

// CORSMiddleware 允许跨域请求
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 设置允许的请求来源
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		// 设置允许的请求方法
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		// 设置允许的请求头
		c.Writer.Header().Set("Access-Control-Allow-Headers", "*")
		// 设置允许的响应头
		c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
		// 设置是否允许凭证
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		// 处理OPTIONS请求
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		// 继续处理请求
		c.Next()
	}
}
